<?php
namespace app\admin\controller;
use app\common\model\ProjectClassify as ProjectClassifyModel;
use app\common\model\Project as ProjectModel;

use app\common\controller\AdminBase;
use think\Config;
use think\Db;
use think\Loader;
use think\Session;
/**
 * 预约项目管理
 * Class Project
 * @package app\admin\controller
 */
class Project extends AdminBase
{
    protected $project_classify_model;
    protected $project_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->project_classify_model         = new ProjectClassifyModel();
        $this->project_model                  = new ProjectModel();

        $project_classify_list       = $this->project_classify_model->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $project_classify_level_list = array2level($project_classify_list);
        $this->assign('project_classify_level_list', $project_classify_level_list);
    }

    /**
     * 预约项目管理
     * @param string $keyword
     * @param int    $page
     * @return project
     */
    public function index($cleanup = "",$cid = "",$keyword = "",$status = "", $page = 1 ,$list_rows = 50)
    {
        //定义查询
        if ($cleanup) {
            Session::delete('cid');
            Session::delete('keyword');
            Session::delete('status');
        }
        if ($cid || $keyword || $status) {
            Session::delete('cid');
            Session::set('cid',$cid);
            Session::delete('keyword');
            Session::set('keyword',$keyword);
            Session::delete('status');
            Session::set('status',$status);
        }

        $where = [];

        if (Session::get('cid')) {
            $project_classify_children_ids = $this->project_classify_model->where(['path' => ['like', "%,".Session::get('cid').",%"]])->column('id');
            $project_classify_children_ids = (!empty($project_classify_children_ids) && is_array($project_classify_children_ids)) ? implode(',', $project_classify_children_ids) . ',' . Session::get('cid') : Session::get('cid');
            $where['cid']  = ['IN', $project_classify_children_ids];
        }

        if (Session::get('keyword')) {
            $where['title'] = ['like', "%".Session::get('keyword')."%"];
        }

        if (Session::get('status')) {
            $where['status'] = Session::get('status')-1;
        }

        $project = Db::view('project_classify','sort')
            ->view('project',
                'id,cid,title,score,status,create_time',
                'project.cid=project_classify.id')
            ->where($where)->order(['status' => 'DESC', 'sort' => 'DESC', 'score' => 'DESC', 'id' => 'DESC'])->paginate($list_rows, false, ['page' => $page]);
        $project_list=[];
        foreach($project as $key => $value) {
            $project_classify=$this->project_classify_model->find($value['cid']);
            $project_classify_path=explode(",",$project_classify['path']);
            $value['project_classify']="";
            foreach($project_classify_path as $kk => $vv) {
                if($vv!=0 && $vv!=null){
                    $project_classify_level=$this->project_classify_model->find($vv);
                    if($value['project_classify']){
                        $value['project_classify']=$value['project_classify'].'-'.$project_classify_level['title'];
                    }else{
                        $value['project_classify']=$project_classify_level['title'];
                    }
                }
            }
            if($value['project_classify']){
                $value['project_classify']=$value['project_classify'].'-'.$project_classify['title'];
            }else{
                $value['project_classify']=$project_classify['title'];
            }
            $project_list[]=$value;
        }
        return $this->fetch('index', [
            'project' => $project,
            'project_list' => $project_list,
            'cid' => Session::get('cid'),
            'keyword' => Session::get('keyword'),
            'status' => Session::get('status')
        ]);
    }

    /**
     * @param $filepathname
     * 将excel文件导入数据库
     * 使用iconv转换字符集防止文件名为中文时乱码
     */
    function import()
    {
        $config = [
            'size' => 209715200,
            'ext'  => 'xls,xlsx,cvs'
        ];
        // 获取表单上传文件
        $file = $this->request->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $info = $file->validate($config)->move($upload_path);

        $filepath = ROOT_PATH.'public/uploads/'.$info->getSaveName();

        Loader::import('classes.PHPExcel',EXTEND_PATH,'.php');
        try{
            $objReader = new \PHPExcel_Reader_Excel2007();
            if (!$objReader->canRead($filepath)) {
                $objReader = new \PHPExcel_Reader_Excel5();
                if (!$objReader->canRead($filepath)) {
                    return;
                }
            }
            $objPHPExcel = $objReader->load($filepath);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $recharge = array();
        $res = [];

        //数量
        $shuliang=0;
        for ($j=2;$j<=$highestRow;$j++){
            if((string)$objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue()){
                $res['classify'] = (string)$objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//获取A列的值
                $res['title'] = (string)$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//获取C列的值
                $res['score'] = (string)$objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//获取C列的值
                $recharge[] = $res;

                //记录数量
                $shuliang=$shuliang+1;
            }
        }

        if($shuliang>1){
            $this->project_model->where('status', 1)->update(['status'=>0]);
        }

        //将文件写入数据库
        $chenggong=0;
        $shibai=0;
        $log='';
        $log_k=0;
        foreach ($recharge as $k=>$value) {
            $log_k=$k+1;
            //判断project_classify是否存在
            $project_classify_where = [];
            $project_classify_where['title']  =$value['classify'];
            $project_classify_see = $this->project_classify_model->where($project_classify_where)->find();
            if($project_classify_see){
                $value['cid']=$project_classify_see['id'];

                $project_data['cid']          = $value['cid'];
                $project_data['title']        = $value['title'];
                $project_data['score']        = $value['score'];
                $project_data['create_time']  = date('Y-m-d H:i:s');
                if(Db::name('project')->insert($project_data)){
                    $chenggong=$chenggong+1;
                    $log=$log."<br>第".$log_k."条，新增成功！";
                }else{
                    $shibai=$shibai+1;
                    $log=$log."<br>第".$log_k."条，失败原因：新增失败。<br>导入信息内容：".$value['classify'].','.$value['title'].','.$value['score'].','.$value['create_time'];
                }
            }else{
                $shibai=$shibai+1;
                $log=$log."<br>第".$log_k."条，失败原因：分类不存在。<br>导入信息内容：".$value['classify'].','.$value['title'].','.$value['score'].','.$value['create_time'];
            }

        }
        $result = [
            'error' => 0,
            'message'   => "共导入成功：".$chenggong."条，失败".$shibai."条!"."<br>".$log
        ];

        return json($result);
    }



    /**
     * 删除预约项目
     * @param $id
     */
    public function delete($id)
    {
        if ($this->project_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}